"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 主节点备份过程中备节点停止
Create At   : 2020/11/13
@zou_jialiang0505328126
Description :
    1.主节点备份数据库
    2.备份的过程中停止备库
    3.使用备份文件恢复数据库
    4.启动数据库
    5.对备库进行build
    6.查询主备节点数据是否一致
Expect      :
    1.主节点备份成功
    2.备节点停止成功
    3.数据恢复成功
    4.启动数据库成功或出现因为备机为Need repair状态的失败
    5.备库重建成功
    6.主备节点数据一致
History     :
    Modified by @peilinqian 2021/2/3: 修改备份路径，解决因原路径为home路径导致备份磁盘不足情况
    Modified by @wan005 2021/1/15: 修改gs_basebackup断言，增加断言信息
    Modified by @wan005 2021/5/17: 调整wal_sender_timeout,规避因环境性能差导致的失败
"""

import os
import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Basebackup(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '----Opengauss_Reliability_Tools_Basebackup_Case001.py 开始执行----')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.common = Common('PrimaryRoot')
        self.parent_path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.parent_path, 'base_backup')

        result = self.pri_sh.executDbSql('show wal_sender_timeout;')
        self.log.info(f"wal_sender_timeout is {result}")
        self.wal_sender_timeout = result.strip().splitlines()[-2]

    def test_basebackup(self):
        self.log.info('-----------修改wal_sender_timeout------------------')
        result = self.pri_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          'wal_sender_timeout=12s')
        self.assertTrue(result)

        self.log.info('----创建备份路径----')
        shell_cmd = f'rm -rf {self.backup_path}; mkdir {self.backup_path}'
        self.log.info(shell_cmd)
        result = self.pri_dbuser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('----启动线程开始备份----')
        basebackup_thread = ComThread(self.pri_sh.execu_gs_basebackup,
                                      args=(self.backup_path,
                                            self.pri_dbuser.db_host,
                                            self.pri_dbuser.db_port,))
        basebackup_thread.setDaemon(True)
        basebackup_thread.start()

        self.log.info('----停止备节点1----')
        result = self.sta_1_sh.stopDbInstance()
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, result)

        self.log.info('----检查备份结果----')
        basebackup_thread.join(60 * 60)
        result = basebackup_thread.get_result()
        self.assertNotIn(self.constant.SQL_WRONG_MSG[1], result)
        self.assertNotIn('error', result)
        self.assertIn(self.constant.BASEBACKUP_SUCCESS_MSG, result)
        result = self.pri_dbuser.sh(
            f'ls -l {self.backup_path} | grep "^-" | wc -l').result()
        self.log.info(result)
        self.assertLess(0, int(result))

        self.log.info('----使用备份文件恢复数据库----')
        result = self.pri_sh.stopDbCluster()
        self.assertTrue(result)
        recovery_cmd = f'rm -rf  {macro.DB_INSTANCE_PATH}/* ;' \
            f'cp -R {self.backup_path}/* {macro.DB_INSTANCE_PATH}'
        result = self.pri_dbuser.sh(recovery_cmd).result()
        self.log.info(result)
        time.sleep(2)

        self.log.info('----启动数据库成功或出现因为备机为Need repair状态的失败----')
        result = self.pri_sh.startDbCluster('get_detail')
        self.log.info(result)
        result = ('Degraded' in result) or \
                 (self.constant.START_SUCCESS_MSG in result)
        self.assertTrue(result)
        time.sleep(2)

        self.log.info('----检查备机是否需要重建----')
        success_msg = self.constant.BUILD_SUCCESS_MSG
        result = self.pri_sh.check_whether_need_build()
        if result:
            result = self.sta_1_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result)
            result = self.sta_2_sh.executeGsctl('build',
                                                success_msg,
                                                '-b full')
            self.assertTrue(result)

        self.log.info('----检查主备是否同步----')
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result)

        self.log.info('----检查数据一致性-----')
        nodes_tuple = (self.pri_dbuser, self.sta1_dbuser, self.sta2_dbuser)
        flag = self.common.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.common.format_sql_result(
            self.pri_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.common.check_data_sample_by_all(select_sql,
                                                        *nodes_tuple)
            self.assertTrue(flag)

    def tearDown(self):
        self.log.info('----环境清理----')
        self.log.info('----删除备份文件----')
        shell_cmd = f'rm -rf {self.backup_path}'
        result = self.pri_dbuser.sh(shell_cmd).result()
        self.log.info(result)

        self.log.info('-----------还原wal_sender_timeout------------------')
        result = self.pri_sh.executeGsguc('reload',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'wal_sender_timeout='
                                          f'{self.wal_sender_timeout}')
        self.log.info(result)
        self.log.info(
            '----Opengauss_Reliability_Tools_Basebackup_Case001.py 执行结束----')
